package com.efounder.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.activity.SettingActivity;
import com.efounder.adapter.CategoryAdapter;
import com.efounder.chat.activity.MyUserInfoActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.esp.update.ConnectServerUpdate;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.Category;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.CheckNetWork;
import com.efounder.util.CustomProgressDialog;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.util.StorageUtil;
import com.efounder.view.titlebar.AbTitleBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class SimpleSettingFragment extends BaseFragment {

    /**配置界面传进来的参数*/
    /**
     * 应用设置要加载的URL
     */
    private String SettingsURL;
    /**
     * 显示当前用户的textView
     */
    private TextView setting_showUser;

    /**
     * 显示当前用户字符串
     */
    private String userID = "默认用户";//登陆时用的帐号
    private String userName;//用户真实姓名
    /**
     * 当前账户
     */
    private LinearLayout settings_userinfo;
    /**
     * 登录设置区域
     */
    private LinearLayout settings_serverSetting;

    //显示当前账户
    private TextView textview;
    private TextView curUsr;

    AbTitleBar title;//标题栏
    private String titleStr;//标题
    private RelativeLayout includeLayout;
    private StorageUtil storageUtil;


    /**
     * 初始化常量APPID
     */
    private static final String APPID = "XBLWANDROID";
    /**
     * 初始化常量本地版本号
     */
    private static final String APPVersion = "0.1";
    /**
     * 服务器请求服务
     */
    private static final String requestType = "mam_checkAppUpgrade";
    /**
     * 服务器请求地址
     */
    private static final String URL = "https://www.pansoft.com/mdm/Android";

    /**
     * 检查更新服务对象
     */
    private ConnectServerUpdate updateServerInfo;

    /**
     * 数据下载地址
     **/
    private static String ServerURL;
    /**
     * 服务器端版本号
     **/
    private String serverVersion;

    /**
     * 加载动画
     */
    private CustomProgressDialog dialog;
    private String avatar = "";
    private ImageView iv_avatar;
    private TextView tv_name;
    private TextView tv_fxid;
    private String fxid;
    private String nick;
    private User user;
    private View rootView;
    // private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    private ListView listView;
    private static StubObject mMenuItem;
    private CategoryAdapter mCustomBaseAdapter;
    private ArrayList<Category> listData;

    List<StubObject> subMenus;
    private LXGlideImageLoader lxGlideImageLoader;


    public static SimpleSettingFragment newInstance(StubObject menuItem, String title) {
        mMenuItem = menuItem;
        Bundle args = new Bundle();
        SimpleSettingFragment fragment = new SimpleSettingFragment();
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshUser();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshUser();
    }

    private void refreshUser() {
        user = WeChatDBManager.getInstance().
                getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        if (user != null) {
            avatar = user.getAvatar();

            tv_name.setText(user.getNickName());
        }

//        if (fxid != null && !fxid.equals("")) {
//            tv_fxid.setText("账号:" + fxid);
//
//        } else {
//            tv_fxid.setText("账号：未设置");
//        }
        if ("1".equals(EnvironmentVariable.getProperty("showLoginID", "0"))) {
            //显示登陆账号  帐号：xxx
            fxid = user.getName();
            tv_fxid.setText(getResources().getText(R.string.chat_number) + ":" + fxid);
        } else {
            //显示联信消息帐号  ID：xxx
            if (fxid != null && !fxid.equals("")) {
                tv_fxid.setText(getResources().getText(R.string.im_chat_number) + ":" + fxid);
            } else {
                tv_fxid.setText(getResources().getText(R.string.im_chat_number) + ":" + getResources().getString(R.string.left_fragment_id_unsetting));
            }
        }


        if (user != null) {
            tv_name.setText(user.getNickName());
        }
//        if (avatar != null && avatar.contains("http")) {
//            imageLoader.displayImage(URLModifyDynamic.getInstance().replace(avatar), iv_avatar, options);
//        } else {
//            imageLoader.displayImage("", iv_avatar, options);
//        }
        lxGlideImageLoader.showUserAvatar(getActivity(), iv_avatar, avatar);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        //如果是群聊，直接返回
        if (chatType == (byte) 1) {
            return;
        }
        if (listData != null && listData.size() > 0) {
            for (int i = 0; i < listData.size(); i++) {
                Category category = listData.get(i);
                List<Category.ChildModel> childModellist = category.getmCategoryItem();
                if (childModellist != null && childModellist.size() > 0) {
                    for (int j = 0; j < childModellist.size(); j++) {
                        Category.ChildModel childModel = childModellist.get(j);
                        if (childModel.getApplyId().equals(fromUserId + "")) {
                            int unReadCount = JFMessageManager.getInstance().getUnReadCount(fromUserId, (byte) 0);
                            childModel.setBadgeNum(unReadCount);
                            mCustomBaseAdapter.notifyDataSetChanged();
                        }
                    }
                }

            }
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if (null != getArguments()) {
            this.titleStr = getArguments().getString("title");
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // initImageLoader();
        lxGlideImageLoader = new LXGlideImageLoader();
        //View rootView = inflater.inflate(R.layout.esp_settings_withtilte, null);
        View rootView = inflater.inflate(R.layout.esp_settings_withtilte_new, null);

        includeLayout = (RelativeLayout) rootView.findViewById(R.id.include);
        includeLayout.setVisibility(View.GONE);
        TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);

        if (!TextUtils.isEmpty(titleStr)) {
            title.setText(titleStr);
        } else {
            title.setText("我的");

        }
        LinearLayout leftbacklayout = (LinearLayout) rootView
                .findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.GONE);

        leftbacklayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //SimpleSettingFragment.this.getFragmentManager().popBackStack();
                getActivity().finish();
            }
        });
        setting_showUser = (TextView) rootView.findViewById(R.id.setting_showUser);
        storageUtil = new StorageUtil(getActivity().getApplicationContext(), "storage");
        //当前账户
        showUser();

        RelativeLayout re_myinfo = (RelativeLayout) rootView.findViewById(
                com.efounder.chat.R.id.re_myinfo);
        re_myinfo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyUserInfoActivity.class);
                intent.putExtra("id", user.getId());
                startActivity(intent);
            }

        });

//        fxid = user.getName();//帐号
        fxid = EnvironmentVariable.getUserName();
        avatar = user.getAvatar();
        iv_avatar = (ImageView) re_myinfo.findViewById(com.efounder.chat.R.id.iv_avatar);
        tv_name = (TextView) re_myinfo.findViewById(com.efounder.chat.R.id.tv_name);
        tv_fxid = (TextView) re_myinfo.findViewById(com.efounder.chat.R.id.tv_fxid);
        tv_name.setText(user.getNickName());
        /**当前账户*/
        settings_userinfo = (LinearLayout) rootView.findViewById(R.id.settings_userSession);
        settings_userinfo.setVisibility(View.GONE);
        /** 登录设置区域 */
        //	settings_serverSetting = (LinearLayout) rootView.findViewById(R.id
        // .settings_serverSetting);
        /** 检查更新 */
        //	setting_checkVersion = (LinearLayout) rootView.findViewById(R.id.setting_checkVersion);

        //settings_serverSetting.setOnClickListener(keyListener);
        settings_userinfo.setOnClickListener(keyListener);
        //setting_checkVersion.setOnClickListener(keyListener);

        listView = (ListView) rootView.findViewById(R.id.listview);
        listView.setHeaderDividersEnabled(false);
        //禁止底部出现分割线
        listView.setFooterDividersEnabled(false);
        listView.setDivider(null);
        listView.setFocusable(false);

        if (null != savedInstanceState) {
            mMenuItem = (StubObject) savedInstanceState
                    .getSerializable("databack");
            titleStr = (String) savedInstanceState.getSerializable("title");
        }

        // 数据
        listData = new ArrayList<>();
        Category category = null;
        List<StubObject> subMenusWithOutPermission = Registry.getRegEntryList((String) mMenuItem.getID());
        subMenus = MenuGnqxUtil.handleGNQX(subMenusWithOutPermission);
        if (null != subMenus && subMenus.size() > 0) {
            for (int i = 0; i < subMenus.size(); i++) {
                if (i % 2 == 0) {
                    category = new Category("");
                    listData.add(category);
                }
                StubObject stubObject = subMenus.get(i);
                String id = stubObject.getString("id", "");
                String viewType = stubObject.getString("viewType", "");
                String AndroidShow = stubObject.getString("AndroidShow", "");
                String title1 = stubObject.getString("title", "");
                String caption = stubObject.getCaption();
                if (!TextUtils.isEmpty(caption)) {
                    title1 = caption;
                }
                String menuIcon = stubObject.getString("menuIcon", "");
                String appId = stubObject.getString("appId", "");
                int unReadCount = 0;
                if (!appId.equals("")) {
                    unReadCount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);

                }
                Category.ChildModel childModel = category.new ChildModel();
                childModel.setId(id);
                childModel.setApplyId(appId);
                childModel.setMenuIcon(menuIcon);
                childModel.setTitle(title1);
                childModel.setBadgeNum(unReadCount);
                childModel.setViewType(viewType);
                childModel.setAndroidShow(AndroidShow);

                category.addItem(childModel);
            }

            mCustomBaseAdapter = new CategoryAdapter(SimpleSettingFragment.this.getContext(), listData);

            // 适配器与ListView绑定
            listView.setAdapter(mCustomBaseAdapter);

            listView.setOnItemClickListener(new ItemClickListener());

        }
        EnvironmentVariable.setProperty("Badge_" + SimpleSettingFragment.this.getBadgeType(), "");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return rootView;
    }

    private class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
//            Toast.makeText(SimpleSettingFragment.this.getContext(), ((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId() + "(根据这个字段来加载后面的界面)",
//                    Toast.LENGTH_SHORT).show();
            /*if (((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId().equals("mySpace")) {
                //发送清空角标的通知
                String appid = ((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getApplyId();
                if (!appid.equals("")) {
                    JFMessageManager.getInstance().unreadZero(Integer.parseInt(appid), (byte) 0);
                    clearBadgeView(appid);
                    mCustomBaseAdapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new UpdateBadgeViewEvent(appid + "", (byte) 2));
                }
                try {
                    Intent intent = new Intent(getActivity(), Class.forName("com.efounder.FriendCircleActivity"));
                    EnvironmentVariable.setProperty("friendStatusNative","false");
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId().equals("myMailbox")) {
                try {
//                    Intent intent = new Intent(getActivity(), Class.forName("com.pansoft.ospemail.activity.EmailIndexActivity"));

                    Intent intent = new Intent(getActivity(), Class.forName("com.efounder.CGClassActivity"));
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }else if (((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId().equals("myDevice")){
                try {
                    Intent intent = new Intent(getActivity(), Class.forName("com.efounder.RNMyDeviceActivity"));
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }else if (((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId().equals("myAudio")){
                try {
                    Intent intent = new Intent(getActivity(), Class.forName("com.pansoft.jntv.audio.AudioActivity"));
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }else if (((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getId().equals("myVideoLive")){
                try {
                    Intent intent = new Intent(getActivity(), Class.forName("com.pansoft.jntv.activity.LiveVideoListActivity"));
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }*/
            //发送清空角标的通知
            String appid = ((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getApplyId();
            if (!"".equals(appid)) {
                JFMessageManager.getInstance().unreadZero(Integer.parseInt(appid), (byte) 0);
                clearBadgeView(appid);
                mCustomBaseAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new UpdateBadgeViewEvent(appid + "", (byte) 2));
            }
//            根据viewType判断跳转到哪个页面
            String viewType = ((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getViewType();
            if (!"".equals(viewType)) {
                AbFragmentManager abFragmentManager = new AbFragmentManager(SimpleSettingFragment.this.getContext());
                StubObject stubObject = new StubObject();
                Hashtable<String, String> hashtable = new Hashtable<String, String>();
                String androidShow = ((Category.ChildModel) mCustomBaseAdapter.getItem(position)).getAndroidShow();
                hashtable.put("viewType", viewType);

                hashtable.put("AndroidShow", androidShow);
                stubObject.setStubTable(hashtable);
                try {
                    abFragmentManager.startActivity(stubObject, 0, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void clearBadgeView(String appid) {
        if (listData != null && listData.size() > 0) {
            for (int i = 0; i < listData.size(); i++) {
                Category category = listData.get(i);
                List<Category.ChildModel> childModellist = category.getmCategoryItem();
                if (childModellist != null && childModellist.size() > 0) {
                    for (int j = 0; j < childModellist.size(); j++) {
                        Category.ChildModel childModel = childModellist.get(j);
                        if (childModel.getApplyId().equals(appid + "")) {
                            childModel.setBadgeNum(0);
                            mCustomBaseAdapter.notifyDataSetChanged();
                        }
                    }
                }

            }
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", mMenuItem);
        outState.putSerializable("title", titleStr);
    }

    private void showUser() {
//		SharedPreferences saveLogData = getActivity().getSharedPreferences(ESPApplication.UserInfo,
//				Context.MODE_PRIVATE);
//		if (saveLogData != null) {
//			userString = saveLogData.getString(ESPApplication.UserInfo_LOGINNAME, "您好");
//		}

        user = WeChatDBManager.getInstance().
                getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        if (user != null) {
            setting_showUser.setText(user.getNickName());
        } else {
            userID = storageUtil.getString("userName");
            userName = storageUtil.getString("userName");
            setting_showUser.setText(userName);
        }

    }

    private View.OnClickListener keyListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (v.getId() == R.id.settings_userSession) {
                Intent intent = new Intent(getActivity(), MyUserInfoActivity.class);
                intent.putExtra("id", user.getId());
                startActivity(intent);
            }
        }
    };


    /**
     * 进入登录服务器设置
     */
    private void doServerSetting() {
        Intent setIntent = new Intent(getActivity(), SettingActivity.class);
        startActivity(setIntent);
    }


    /**
     * 如果可以下载则更新包
     *
     * @return false无连接
     */
    private Boolean docheckNetwork(Context context) {
        // TODO Auto-generated method stub
        CheckNetWork check = new CheckNetWork();
        if (check.isWifiConnected(context) == true
                || check.isMobileConnected(context) == true) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 版本更新
     *
     * @throws Exception
     */
    private void docheckVersion(Context context) {
        // TODO Auto-generated method stub
        /**
         * 获取到服务器更新信息
         */
        ArrayList<String> list = new ArrayList<String>();
        updateServerInfo = new ConnectServerUpdate();
        list = updateServerInfo.ConnectServerUpdates(requestType, APPID,
                APPVersion, URL);
        if (list != null) {
            if (list.get(0) != null) {
                if (list.get(0).equals("1")) {
                    ServerURL = list.get(1);
                    serverVersion = list.get(2);
                    showUpdateDialog(ServerURL, ServerURL, serverVersion);
                }
            }

        } else {
            Toast.makeText(context, "没有检测到新版本", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 关于我们
     */
    private void doAbout(Context context) {
        // TODO Auto-generated method stub
        doIphone5sAlert(context, "",
                "技术支持：普联软件股份有限公司");
    }

    /**
     * Iphone5s弹窗
     */

    private void doIphone5sAlert(Context context, String pTitle,
                                 final String pMsg) {
        // TODO Auto-generated method stub
        final Dialog Alert = new Dialog(context,
                android.R.style.Theme_Translucent_NoTitleBar);
        Alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Alert.setContentView(R.layout.alert_style);
        // ((TextView)
        // Alert.findViewById(R.id.dialog_title)).setText(pTitle);
        ((TextView) Alert.findViewById(R.id.dialog_message)).setText(pMsg);
        ((Button) Alert.findViewById(R.id.ok)).setText("关闭");
        ((Button) Alert.findViewById(R.id.ok))
                .setBackgroundColor(Color.TRANSPARENT);
        ((Button) Alert.findViewById(R.id.ok))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // write your code to do things after users clicks
                        // OK
                        Alert.dismiss();
                    }
                });
        Alert.show();

    }


    /**
     * @param serverURL
     * @param serverVersion 显示更新窗口
     */
    private void showUpdateDialog(final String ServerURL, String serverURL,
                                  String serverVersion) {
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("\t\t\t\t\t\t检测到新版本");
        builder.setMessage("系统版本由:" + APPVersion + "升级为:" + serverVersion
                + "\n是否下载更新?");
        builder.setPositiveButton("下载",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
//							Intent it = new Intent(getActivity(),
//									NotificationUpdateActivity.class);
//							it.putExtra("ServerURL", ServerURL);
//							startActivity(it);

//							app.setDownload(true);
                    }
                }).setNegativeButton(R.string.common_text_cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                });
        builder.show();
    }


    public String getUser() {
        String username = null;
//			SharedPreferences saveLogData = getActivity().getSharedPreferences(ESPApplication.UserInfo,Context.MODE_PRIVATE);
//			if(saveLogData!=null){
//				username = saveLogData.getString("userinfo_id", null);
//				if(username==null){
//					username="当前用户未识别";
//					}
//				}
        return username;
    }


    /**
     * 异步加载头像
     */
//    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(com.efounder.chat.R.drawable.default_useravatar);
//
//    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

}
